package ro.isdc.training.ejb3.student.dao.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.ejb3.student.dao.StudentDAO;
import ro.isdc.training.ejb3.student.domain.Student;
import ro.isdc.training.ejb3.student.domain.StudentId;
import ro.isdc.training.ejb3.systemuser.domain.SystemUser;

/**
 * Student Data Access Object Bean Implementation.
 * 
 * @author Andrei Chirila
 */
@Stateless
@Local(StudentDAO.class)
public class StudentDAOBean implements StudentDAO {

  @PersistenceContext
  private EntityManager entityManager;
  
  /**
   * {@inheritDoc}
   */
  public Student findStudentByIdentification(final StudentId studentId) {
    List<Object> paramValuesList = new ArrayList<Object>();
    List<String> paramNamesList = new ArrayList<String>();
    
    String sql ="select s from Student s";
    if (studentId != null) {
      if (studentId.getEntityId() > 0) {
        sql += " where s.entityId = :entityId";
        paramNamesList.add("entityId");
        paramValuesList.add(studentId.getEntityId());
      } else {
        sql += " where s.SSN = :SSN";
        paramNamesList.add("SSN");
        paramValuesList.add(studentId.getSSN());
      }
    }
    
    return 
      (Student) entityManager.createQuery(sql).setParameter(paramNamesList.get(0), paramValuesList.get(0)).getSingleResult();
  }

}
